package io.github.annyylxyms.gyn.gateway.web.handler;

import io.github.annyylxyms.gyn.gateway.DefaultGatewayPluginChain;
import io.github.annyylxyms.gyn.gateway.GatewayPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * gateway web handler
 * @author annyylxyms
 */
@Component("gatewayWebHandler")
public class GatewayWebHandler implements WebHandler {
    //一个新玩法！用Autowired List<类>可以把bean注入到集合里去
    @Autowired
    List<GatewayPlugin> plugins;

    //以下逻辑都可以用flux直接写成一个大return，但日常工作中不需要这么干，太累了哈哈哈哈哈哈哈哈哈哈哈哈
    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {
        System.out.println("===>>>>> gyn gatewayWebHandler");
        //处理plugins为空的情况
        if (plugins == null || plugins.isEmpty()) {
            String mock = """
                    {"result":"no plugin"}
                    """;
            //Mono 惰性求值 比如Map flatMap, 而just是立马求值的
            //Mono.just指定一个对象，Mono.just(mock)指明一个对象，但是这个对象是一个字符串，所以需要用bufferFactory()转换一下
            return exchange.getResponse()
                    .writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(mock.getBytes())));
        }

        return new DefaultGatewayPluginChain(plugins).handle(exchange);

//        for (GatewayPlugin plugin : plugins) {
//            if (plugin.support(exchange)) {
//                return plugin.handle(exchange);
//            }
//        }

//        String mock = """
//                {"result":"no supported plugin"}
//                """;
//        return exchange.getResponse()
//                .writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(mock.getBytes())));
    }

}
